package com.zhuss.controller.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution {
    static int res=0;
    
    
    public static void main(String[] args) {
    	TreeNode a = new TreeNode(4);
        TreeNode b = new TreeNode(3);
        TreeNode c = new TreeNode(1);
        TreeNode d = new TreeNode(2);
        a.left = b;
        a.right = null;
        b.left = c;
        b.right = d;
       
    	System.out.println(maxSumBST(a));
	}
    
    public static int maxSumBST(TreeNode root) {
        if(root==null) return 0;
        solve(root);
        maxSumBST(root.left);
        maxSumBST(root.right);
        return res;
    }

     public static void solve(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        TreeNode p=root;
        int sum=0;
        while(!stack.isEmpty()||p!=null){
            while(p!=null){
                stack.push(p);
                p=p.left;
            }
            list.add(stack.peek().val);
            sum+=stack.peek().val;
            p=stack.pop().right;
        }
        for(int i=0;i<list.size()-1;i++){
            if(list.get(i+1)<=list.get(i)){
                sum=0;
                break;
            }
        }
        res=Math.max(res,sum);
    }
}

class TreeNode{
    int val=0;
    TreeNode left=null;
    TreeNode right=null;

    public TreeNode(int val){
        this.val=val;
    }
}
